 
import { FightState } from "../consts/fight_state";
import { Player } from "./player.entity";
import { GlobalConfig } from "../../config/global/global_config";
import { PlayerDao } from "../dao/player_dao";
import { FightService } from "../services/fight_service";
import { PushService } from "../services/push_service";
import { PushRoute } from "../consts/push_route";
import { Attack } from "./effect/attack";
import { Monster } from "./monster";
import { Unit } from "./unit";
import { PlayerService } from "../services/player_service";
import { EffectType } from "../consts/effect_type";
 
 
export class Fight{
    player:Unit;
    enemy:Unit;
    fightState:FightState;
  
    timer;
    frame=50;

    constructor(player:Unit,enemy:Unit){
        this.player=player;
        this.enemy=enemy;
        this.player.setCurHp(this.player.maxHp);
        this.fightState=FightState.Default;
        // this.frame=GlobalConfig.ins().fight[0].frame;
    }


    start(){
        if(this.fightState===FightState.Fighting){
            return;
        }
        this.player.effects.push(new Attack(this.player,this.enemy));
        this.enemy.effects.push(new Attack(this.enemy,this.player));
        this.timer=setInterval(()=>{
            //  console.log("in loop..");
            let effect=this.player.getEffect(EffectType.Attack);
            if(effect){
                (effect as Attack).setCanAttack(true);
            }
            effect=this.enemy.getEffect(EffectType.Attack);
            if(effect){
                (effect as Attack).setCanAttack(true);
            }
               this.player.run();
               if(this.player.isDied){
                   this.end();
                   return;
               }
                this.enemy.run();
                if(this.enemy.isDied){
                    this.end();
                    return;
                }
        },this.frame/1000);
        this.fightState=FightState.Fighting;
    }


    stop(){
        clearInterval(this.timer);
        this.fightState=FightState.End;
    }

    async end(){
        if(this.fightState===FightState.End){
            return;
        }
        console.log("战斗已结束..");
        clearInterval(this.timer);
        this.fightState=FightState.End;
        this.player.effects=[];
        this.enemy.effects=[];
        await PlayerDao.ins().updateForFightOver(this.player,this.enemy);
        await PushService.ins().pushToOne(PushRoute.FightOnFightOver,"fight",this.player.pushId,PushRoute.FightOnFightOverMsg(this.player));
        
        FightService.ins().removeFight(this);
   
 
    }

}